//
//  MyWebController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/19.
//

import UIKit
import WebKit
import JXPhotoBrowser

class MyWebController: BaseViewController {
    var handlerMethod:[String] = ["h5ToApp","callPhone"]
    var webView: WKWebView!
    var urlStr: String = ""     //url
    var titleStr: String = ""   //标题
    var localHtmlStr: String = ""  //本地html标签
    var webViewHeight: CGFloat = 0.01
    var bodyColorHex: String = "#F2F7FA"
    var progressView: UIProgressView! = {
        let tempProgressView = UIProgressView.init(frame: CGRect.init(x: 0, y: NavBarHight-2, width: kScreenWidth, height: 2))
        tempProgressView.backgroundColor = UIColor.white
        tempProgressView.progressTintColor = Theme.mainColor
        return tempProgressView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.addSubview(self.progressView)
        self.navBar.title = self.titleStr
        let configuretion = WKWebViewConfiguration.init()
        configuretion.preferences = WKPreferences()
        configuretion.preferences.minimumFontSize = 0
        configuretion.preferences.javaScriptEnabled = true
        configuretion.preferences.javaScriptCanOpenWindowsAutomatically = true
        configuretion.userContentController = WKUserContentController()
        for item in self.handlerMethod {
            configuretion.userContentController.add(self, name: item)
        }
        webView = WKWebView.init(frame: CGRect.init(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - NavBarHight), configuration: configuretion)
        webView.navigationDelegate = self
        webView.uiDelegate = self
        if #available(iOS 11.0, *) {
            webView.scrollView.contentInsetAdjustmentBehavior = .never
        }
        webView.scrollView.showsHorizontalScrollIndicator = false
        self.view.addSubview(webView)
        
        //加载本地文件
        //let path = Bundle.main.path(forResource: "abc", ofType: "html")!
        //let request = URLRequest.init(url: URL.init(fileURLWithPath: path))
        //webView.load(request)
        
        
//        let fontFamilyNames = UIFont.familyNames
//        for family in fontFamilyNames {
//            print(family)
//
//            for fontName in UIFont.fontNames(forFamilyName: family) {
//                print("   %@", fontName)
//            }
//        }
        
        if self.urlStr != "" {
            guard let url = URL.init(string: self.urlStr) else {
                return
            }
            self.webView.load(URLRequest.init(url: url))
        }else if self.localHtmlStr != "" {
            let formatWeb = """
                    <!DOCTYPEhtml>
                        <html>
                        <head>
                            <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"name="viewport">
                            <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
                        </head>
                        <style type="text/css">
                            img{
                                display:inline-block;
                                max-width:100%@;
                            }
                        </style>
                        <body style="background-color: %@">
                            %@
                        </body>
                        </html>
                    """
            let tempStr = String(format: formatWeb,
                                 "%",
                                 bodyColorHex,
                                 self.localHtmlStr)
            self.webView.scrollView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
            self.webView.loadHTMLString(tempStr, baseURL: nil)
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
    }
    
    ///监听进度条
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progressView.progress = Float(self.webView.estimatedProgress)
        }
        if self.webView.estimatedProgress == 1 {
            self.webView.isHidden = true
        }else{
            self.webView.isHidden = false
        }
    }
    
    
    @objc func jumpLogin(){
        XTManageCenter.shared.jumpToLoginView()
    }
    
    ///关闭当前页面
    func closePage() {
        self.webView.goBack()
    }
    
    ///退出登录，返回到登录页
    func logout() {
        XTManageCenter.shared.jumpToLoginView()
    }
    
    ///打电话
    func callPhone(tel: String) {
        XTManageCenter.callPhoneAction(phone: tel)
    }
}

extension MyWebController: WKScriptMessageHandler, WKNavigationDelegate {
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        //什对ios9 延时一点才会有效
        self.perform(#selector(toH5Token(webvView:)), with: webView , afterDelay: 1)
        webView.evaluateJavaScript("document.body.offsetHeight") { (result, error) in
            if result == nil{
                return
            }
            let documentheight = result as! CGFloat
            webView.evaluateJavaScript("document.body.offsetWidth", completionHandler: { (result , error) in
                let documentwidth = result as! CGFloat
                _ = documentwidth/documentheight as CGFloat
                self.webViewHeight = self.webView.frame.size.height
            })
        }
        
    }

    @objc private func toH5Token(webvView: WKWebView){
        self.webView.evaluateJavaScript("document.body.style.fontFamily = \"Calibri\"") { _, error in
            print(error as Any)
        }
        //获取当前页面的title
        if self.webView != nil {
            self.webView.evaluateJavaScript("document.title", completionHandler: {
                (titleStr, error) in
                printLog("=======html5 XTwebView=======")
                if titleStr != nil && (titleStr as? String) != "" {
                    self.navBar.title = (titleStr as! String)
                }else{
                    self.navBar.title = self.titleStr
                }
            })
        }
    }
    
    ///存数据到localStorage
    @objc func setLocalData() {
        let tempToken = UserModule.shared.token ?? ""
        let tempStr1 = String(format: "window.localStorage.setItem('UserIndex', '%@')", tempToken)
        self.webView.evaluateJavaScript("\(tempStr1)") { _, err in
            print(err as Any)
        }
    }
    ///js调用ios方法
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.name)
        let msgBody = message.body as? String
        switch message.name {
        case "callPhone":
            //打电话
            self.callPhone(tel: msgBody ?? "")
        case "logout":
            //退出
            self.logout()
        default:
            ()
        }
    }
    
    ///服务器开始请求的时候调用 过滤域名
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(.allow)
    }
    
    ///开始加载
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {}
}

